#include "smart-device-net-protocol.h"

void SmartDevicenetProtocol::addOperation(const string &operation)
{
	root["operation"] = operation;
}

void SmartDevicenetProtocol::addCommand(const string &command)
{
	root["command"] = command;
}

void SmartDevicenetProtocol::addDeviceType(const string &type)
{
	root["device"]["deviceType"] = type;
}

void SmartDevicenetProtocol::addDeivceNumber(const string &number)
{
	root["device"]["deviceNumber"] = number;
}

void SmartDevicenetProtocol::addDevice(const string &type, const string &number)
{
	addDeviceType(type);
	addDeivceNumber(number);
}

void SmartDevicenetProtocol::addListItem(const string &operation, const string &type, const string &number)
{
	Json::Value item;
	item["operation"]    = operation;
	item["deviceType"]   = type;
	item["deviceNumber"] = number;
	objArray.append(item);
}

void SmartDevicenetProtocol::addErrmsg(const string &errmsg)
{
	root["result"]["errmsg"] = errmsg;
}

void SmartDevicenetProtocol::addResult(const string &errmsg, const string &data)
{
	root["result"]["errmsg"] = errmsg;
	root["result"]["data"]   = data;
}

void SmartDevicenetProtocol::addListResult(const string &errmsg)
{
	root["result"]["errmsg"]  = errmsg;
	root["result"]["devices"] = objArray;
}

string SmartDevicenetProtocol::toString()
{
	return root.toStyledString();
}

string SmartDevicenetProtocol::getOperation(void) const
{
	return root["operation"].asString();
}

string SmartDevicenetProtocol::getCommand(void) const
{
	return root["command"].asString();
}

string SmartDevicenetProtocol::getDeviceValue(const string &key)
{
	return root["device"][key].asString();
}

uint32_t SmartDevicenetProtocol::getDeviceType(void) const
{
	string type = root["device"]["deviceType"].asString();
	return stoi(type, 0, 16);
}

uint32_t SmartDevicenetProtocol::getDeviceNumber(void) const
{
	string number = root["device"]["deviceNumber"].asString();
	return stoi(number, 0, 16);
}

uint32_t SmartDevicenetProtocol::getUserId(void) const
{
	string userId = root["userid"].asString();
	return stoi(userId, 0, 16);
}

bool SmartDevicenetProtocol::empty(void)
{
	return root.empty();
}

SmartDevicenetProtocol SmartDevicenetProtocol::fromJsonData(const string &jsonData)
{

	Json::Reader           reader;
	Json::Value            root;
	SmartDevicenetProtocol protocol;

	bool ok = reader.parse(jsonData, protocol.root);
	if(!ok)
	{
		fprintf(stderr, "Fail to read.parse\n");
	}

	return protocol;
}